﻿using ActionFilterPlugin.models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System.Net;

namespace ActionFilterPlugin
{
    /// <summary>
    /// https://learn.microsoft.com/zh-cn/aspnet/core/mvc/controllers/filters?view=aspnetcore-6.0
    /// </summary>
    public class ComActionFilter : ActionFilterAttribute
    {
        IConfiguration _configuration;

        public ComActionFilter(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            AuthFilter(context);
        }

        public void AuthFilter(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                context.Result = new JsonResult(new 
                {
                    code = HttpStatusCode.Unauthorized,
                    message = "缺少参数"
                });
                return;
            }

            //这个拿到的是真实controller
            string controller = context.RouteData.Values["Controller"].ToString();
            string action = context.RouteData.Values["action"].ToString();

            string token = context.HttpContext.Request.Headers["Authorization"];
            if (string.IsNullOrEmpty(token))
            {
                token = context.HttpContext.Request.Query["Authorization"];
                if (!string.IsNullOrEmpty(token))
                    context.HttpContext.Request.Headers.Add("Authorization", token);
            }
            try
            {
                if (string.IsNullOrEmpty(token))
                {
                    context.Result = new JsonResult(new 
                    {
                        code = HttpStatusCode.Unauthorized,
                        message = "token验证失败"
                    });
                    return;
                }
                string jiemiKey = _configuration["JwtAuthorize:PublicSecret"];
                token = token.Replace("Bearer", "");

                LoginModel _loginModel = JsonConvert.DeserializeObject<LoginModel>(SecurityHelper.DESDecrypt(token.TrimStart(), jiemiKey));

                if (_loginModel.dt.AddMinutes(5) < DateTime.Now)
                {
                    context.Result = new JsonResult(new 
                    {
                        code = HttpStatusCode.Unauthorized,
                        message = "token已过期"
                    });
                    return;
                }


                List<String> skey = new List<string>() {
                    _configuration["openline:swagger"],
                    _configuration["openline:androidappkey"]
                };
                if (!skey.Contains(_loginModel.SourceKey))
                {
                    context.Result = new JsonResult(new 
                    {
                        code = HttpStatusCode.Unauthorized,
                        message = "SourceKey无效"
                    });
                    return;
                }

                string BaseSecret = _configuration["JwtAuthorize:BaseSecret"];
                LoginAuthModel[] auths = JsonConvert.DeserializeObject<LoginAuthModel[]>(SecurityHelper.DESDecrypt(_loginModel.Token.Replace(_configuration["JwtAuthorize:DefaultScheme"], "").TrimStart(), BaseSecret));

                //LoginAuthModel sourceFrom = null;
                foreach (var item in auths)
                {
                    if (item.Key == LoginAuthEnum.Expires)
                    {
                        DateTime Dt = DateTime.Parse(item.Value);
                        if (Dt < DateTime.Now)
                        {
                            context.Result = new JsonResult(new 
                            {
                                code = HttpStatusCode.NonAuthoritativeInformation,
                                message = "登录过期"
                            });
                            return;
                        }
                    }
                    if (item.Key == LoginAuthEnum.UserInfo) {
                        Console.WriteLine($"当前线程：{Thread.CurrentThread.ManagedThreadId}");

                        UserLoginModel _userLoginModel = Newtonsoft.Json.JsonConvert.DeserializeObject<UserLoginModel>(item.Value);
                        
                        context.HttpContext.Items["userid"] = _userLoginModel.UserId;
                        context.HttpContext.Items["username"] = _userLoginModel.UserName;
                    }
                }

            }
            catch (Exception ex)
            {
                context.Result = new JsonResult(new 
                {
                    code = HttpStatusCode.NonAuthoritativeInformation,
                    message = "token验证失败",
                    data = ex.Message
                });
                return;
            }
            base.OnActionExecuting(context);
        }
    }

    public class LoginAuthModel
    {
        public LoginAuthModel(string key, string value)
        {
            this.Key = key;
            this.Value = value;
        }

        public string Key { get; set; }

        public string Value { get; set; }
    }

    public class LoginModel
    {
        public string Token { get; set; }

        public DateTime dt { get; set; }

        /// <summary>
        /// 业务线key
        /// </summary>
        public string SourceKey { get; set; }
    }

    public class AuthAttrModel
    {
        public string authUrl { get; set; }

        public string msgTip { get; set; }
    }

    public class LoginAuthEnum
    {
        public static string UserInfo = "userinfo";

        public static string GroupInfo = "GroupInfo";

        public static string GroupTagInfo = "GroupTagInfo";

        public static string Expires = "Expires";

        public static string SourceFromKey = "SourceFrom";
    }
}